package com.lemon.boot.common.service.impl;

import cn.hutool.core.util.IdUtil;
import com.lemon.boot.common.handler.RedisTokenRepositoryHandler;
import com.lemon.boot.common.properties.RememberMeConfigProperties;
import com.lemon.boot.common.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author 李猛
 * @datetime 2024/8/5 13:20
 * @description TODO
 */
@Slf4j
@Component
public class RememberMeServiceImpl extends PersistentTokenBasedRememberMeServices {
    private static final String[] pass = {"true", "on", "yes", "1"};
    public RememberMeConfigProperties rememberMeConfigProperties;

    public RememberMeServiceImpl(RememberMeConfigProperties rememberMeConfigProperties, UserDetailsService userDetailsService, RedisService redisService) {
        super(IdUtil.getSnowflakeNextIdStr(), userDetailsService, new RedisTokenRepositoryHandler(redisService, rememberMeConfigProperties));
        super.setTokenValiditySeconds(rememberMeConfigProperties.getTokenValiditySeconds());
        super.setAlwaysRemember(rememberMeConfigProperties.isAlwaysRemember());
        super.setCookieName(rememberMeConfigProperties.getRememberMeCookieName());
        super.setParameter(rememberMeConfigProperties.getRememberMeParameter());
        super.setUseSecureCookie(rememberMeConfigProperties.isUseSecureCookie());
        this.rememberMeConfigProperties = rememberMeConfigProperties;
    }

    /**
     * 验证是否是持久化登录
     *
     * @param request   the request submitted from an interactive login, which may include
     *                  additional information indicating that a persistent login is desired.
     * @param parameter the configured remember-me parameter name.
     * @return
     */
    @Override
    protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {
        log.info("SecurityRememberMeService.rememberMeRequested.uri:{},parameter:{}", request.getRequestURI(), parameter);
        if (rememberMeConfigProperties.isAlwaysRemember()) {
            return true;
        }
        Object value = request.getAttribute(parameter);
        if (Objects.isNull(value)) {
            return false;
        }
        return Arrays.stream(pass).anyMatch(item -> item.equalsIgnoreCase(value.toString()));
    }
}
